package tt.dz.egobus.servicemanager.business.listener;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationContext;
import org.springframework.core.convert.converter.Converter;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;
import tt.dz.egobus.servicemanager.bean.DefaultSPIServiceLoader;
import tt.dz.egobus.servicemanager.bean.RedisTopicMessage;
import tt.dz.egobus.servicemanager.bean.SPIServiceLoader;
import tt.dz.egobus.servicemanager.business.convert.RedisTopicMessageConverter;

import java.util.Iterator;
import java.util.ServiceLoader;

/**
 * @author Anson
 * @date 17-8-24
 * @name redis 过期处理器
 * @see RedisEventMessageHandler#handlerEvent(RedisTopicMessage, RedisTemplate, ApplicationContext)
 * @since 1.0.6
 */
@Component
public class RedisExpirePubSubHandler implements MessageListener {

    @Autowired
    @Qualifier("redisMessageListenerContainer")
    RedisMessageListenerContainer redisMessageListenerContainer;

    @Autowired
    @Qualifier("redisTemplate")
    RedisTemplate redisTemplate;

    @Autowired
    ApplicationContext applicationContext;

    SPIServiceLoader spiServiceLoader = new DefaultSPIServiceLoader();

    Converter<Message, RedisTopicMessage> converter = new RedisTopicMessageConverter();

    ServiceLoader<RedisEventMessageHandler> serviceLoader = spiServiceLoader.serviceLoader(RedisEventMessageHandler.class);

    @Override
    public void onMessage(Message message, byte[] bytes) {
        if (message == null) {
            return;
        }
        RedisTopicMessage redisTopicMessage = converter.convert(message);
        String eventKey = redisTopicMessage.getEventName();
        if (StringUtils.isAnyEmpty(eventKey)) {
            return;
        }
        Iterator<RedisEventMessageHandler> handlerIterator = serviceLoader.iterator();
        RedisEventMessageHandler handler = null;
        while (handlerIterator.hasNext()) {
            handler = handlerIterator.next();
            if (eventKey.equals(handler.id())) {
                handler.handlerEvent(redisTopicMessage, redisTemplate, applicationContext);
            }
        }
    }


}
